//
//  RootViewController.m
//  GroupManager
//
//  Created by gokei on 11/10/12.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "RootViewController.h"
#import <AddressBookUI/AddressBookUI.h>
#import "GroupMemberListViewController.h"

#define MY_BANNER_UNIT_ID @"a14eacdef1a5a77"

GADBannerView *bannerView_;


@implementation RootViewController

@synthesize tableView = _tableView;


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = NSLocalizedString(@"groups", nil);
	self.navigationItem.leftBarButtonItem = self.editButtonItem;
	abmanager = [[ABManager sharedManager] retain];
	modifyIndex = 0;
	
	CGRect frame = self.tableView.frame;
	self.tableView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height - GAD_SIZE_320x50.height);
	NSLog(@"%f", self.tableView.frame.size.height);
	
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(reload) 
												 name:UIApplicationDidBecomeActiveNotification 
											   object:[UIApplication sharedApplication]];
	
	// Create a view of the standard size at the bottom of the screen.
	bannerView_ = [[GADBannerView alloc]
                   initWithFrame:CGRectMake(0.0,
                                            self.navigationController.view.frame.size.height -
                                            GAD_SIZE_320x50.height,
                                            GAD_SIZE_320x50.width,
                                            GAD_SIZE_320x50.height)];
	bannerView_.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
	
	// Specify the ad's "unit identifier." This is your AdMob Publisher ID.
	bannerView_.adUnitID = MY_BANNER_UNIT_ID;
	
	// Let the runtime know which UIViewController to restore after taking
	// the user wherever the ad goes and add it to the view hierarchy.
	bannerView_.rootViewController = self.navigationController;
	[self.navigationController.view addSubview:bannerView_];
	
	// Initiate a generic request to load it with an ad.
	[bannerView_ loadRequest:[GADRequest request]];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	[self.tableView reloadData];
	if (bannerView_) {
		[UIView beginAnimations:nil context:nil];
		[bannerView_ setFrame:CGRectMake(0.0,
										 self.navigationController.view.frame.size.height -
										 GAD_SIZE_320x50.height,
										 GAD_SIZE_320x50.width,
										 GAD_SIZE_320x50.height)];
		[UIView commitAnimations];
	}
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	/*if (bannerView_) {
		[UIView beginAnimations:nil context:nil];
		[bannerView_ setFrame:CGRectMake(0.0,
										 self.navigationController.view.frame.size.height,
										 GAD_SIZE_320x50.width,
										 GAD_SIZE_320x50.height)];
		[UIView commitAnimations];
	}*/
}

/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations.
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 */


#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [abmanager getGroupCount];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }
    
	// Configure the cell.
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	NSInteger row = [indexPath row];
	NSString *gpName = [abmanager getGroupNameAtIndex:row];
	cell.textLabel.text = gpName;
	cell.detailTextLabel.text = [NSString stringWithFormat:@"%i", [[abmanager.groups objectAtIndex:row] getPersonCount]];
	UIImage *img = [UIImage imageNamed:@"head.png"];
	cell.imageView.image = img;

    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
		[abmanager deleteGroupAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}



/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
	
	NSInteger row = [indexPath row];
	if (self.editing) {
		modifyIndex = row;
		[self showGroupNameInputDialog:[abmanager getGroupNameAtIndex:row]];
	} else {
		GroupMemberListViewController *c = [[GroupMemberListViewController alloc] initWithNibName:@"GroupMemberListViewController" bundle:nil];
		c.group = [abmanager.groups objectAtIndex:row];
		c.rootViewController = self;
		[self.navigationController pushViewController:c animated:YES];
		[c release];
	}

}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
	[super setEditing:editing animated:animated];
	[self.tableView setEditing:editing animated:animated];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[bannerView_ release];
    [super dealloc];
}

#pragma mark -
#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex) {
		UITextField *textField = (UITextField*)[alertView viewWithTag:11];
		if (self.editing) {
			[abmanager updateGroupNameAtIndex:modifyIndex name:textField.text];
		} else {
			[abmanager createGroup:textField.text];
		}
		[self.tableView reloadData];
	}
}

#pragma mark -
#pragma mark UI Design

- (void)showGroupNameInputDialog:(NSString*)name {
	NSString *alertTitle = NSLocalizedString(@"add", nil);
	if (self.editing) {
		alertTitle = NSLocalizedString(@"change group name", nil);
	}
	UIAlertView *alert = [[UIAlertView alloc]initWithTitle:alertTitle message:@"¥n¥n" delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:NSLocalizedString(@"ok", nil), nil];  
	UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(12, 45, 260, 25)];
	textField.backgroundColor = [UIColor whiteColor];
	textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
	textField.text = name;
	textField.tag = 11;
	[textField becomeFirstResponder];
	[alert addSubview:textField];
	[textField release];
	[alert show];
	[alert release];
}

- (IBAction)showAddDialog:(id)sender {
	[self showGroupNameInputDialog:nil];
}

- (void)reload {
	[self.tableView reloadData];
}

@end

